<?php

class Sftp
{
    private $conn = NULL;

    public function __construct(string $host, string $user, string $pwd, int $port = 22)
    {
        $conn = ssh2_connect($host, $port);
        if (ssh2_auth_password($conn, $user, $pwd)) {
            $this->conn = $conn;
        } else {
            echo "sftp登录失败";

        }
    }

    /**
     * 下载文件
     * @param string $filePath
     * @param string $saveFilePath
     * @return bool
     */
    public function getFile(string $filePath, string $saveFilePath): bool
    {
        if (empty($this->conn)) {
            return false;
        }
        $sftp = ssh2_sftp($this->conn);

        $files = array();
        $dirHandle = opendir("ssh2.sftp://$sftp/./");

        while (false !== ($file = readdir($dirHandle))) {
            if ($file != '.' && $file != '..') {
                $files[] = $file;
            }
        }

        $check = file_exists("ssh2.sftp://{$sftp}/./" . $filePath);
        if (!$check) {
            echo "sftp文件路径不存在：" . $filePath;
            return false;
        }

        $source = "ssh2.sftp://{$sftp}/./{$filePath}";

        return copy($source, $saveFilePath);
    }

}

$sftp = new Sftp('192.168.1.115', 'sftp_user', '123', 22);
if ($sftp->getFile('file/b.txt',  'b.txt')) {
    echo "success";
} else {
    echo "fail";
}



//$param = Yii::$app->params['ep_ftp'];
//$sftp = new Sftp($param['sftp_host'], $param['sftp_user'], $param['sftp_pwd'], $param['sftp_port']);
//if ($sftp->getFile($param['sftp_file_path'], $param['path'] . '/' . $param['get_file_name'])) {
//    echo "success";
//} else {
//    echo "fail";
//}


